<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillCode_FormItem" prop="BillCode">
							<template #label>
								<WtmLabelTooltip label="单据编号" tooltip="单编号" />
							</template>
							<el-input v-model="searchData.BillCode" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<WtmDeptSelector v-model="searchData.GroupId" label="部门" :rules="[]" :auth="false" />
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillStatus_FormItem" prop="BillStatus">
							<template #label>
								<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
							</template>
							<el-select v-model="searchData.BillStatus" clearable>
								<el-option v-for="item in BILL_STATUS_OPTIONS" :key="item" :value="item" :label="item"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="WorkflowStatus_FormItem" prop="WorkflowStatus">
							<template #label>
								<WtmLabelTooltip label="审批状态" tooltip="审批状态" />
							</template>
							<el-select v-model="searchData.WorkflowStatus" clearable>
								<el-option v-for="item in WORKFLOW_STATUS_OPTIONS" :key="item" :value="item" :label="item"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Approver_FormItem" prop="Approver">
								<template #label>
									<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
								</template>
								<el-input v-model="searchData.Approver" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ApprovalTime_FormItem" prop="ApprovalTime">
								<template #label>
									<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
								</template>
								<el-date-picker type="daterange" v-model="searchData.ApprovalTime" clearable></el-date-picker>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBill/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBill/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBill/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrJobAssignmentRequestBill/SysHrJobAssignmentRequestBillExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable
			ref="tableRef"
			:data="tableData.data"
			:header="tableData.header"
			:config="tableData.config"
			:span-method="spanMethod"
			class="table-operation-area"
		>
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="130" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container" v-if="shouldShowOperationButtons(scope.row, scope.$index)">
							<WtmButton
								v-auth="'/api/SysHrJobAssignmentRequestBill/Edit'"
								v-if="scope.row.BillStatus === BILL_STATUS.DRAFT"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrJobAssignmentRequestBill/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrJobAssignmentRequestBill/BatchDelete'"
								v-if="scope.row.BillStatus === BILL_STATUS.DRAFT"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="岗位分配申请;true;HengTong.Areas.Hr.Controllers;SysHrJobAssignmentRequestBill">
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrJobAssignmentRequestBillApi as api } from '/@/views/hr/syshrjobassignmentrequestbill/api';
import { ISysHrJobAssignmentRequestBillView, ISysHrJobAssignmentRequestBillQuery } from '/@/views/hr/syshrjobassignmentrequestbill/api/interface';
import other from '/@/utils/other';

// 懒加载子组件
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const BILL_STATUS_OPTIONS = ['草稿', '正文'] as const;

const WORKFLOW_STATUS_OPTIONS = ['待提交', '提交中', '审核中', '已完成', '已取消'] as const;

// 需要合并的字段配置（根据实际需求调整）
const TABLE_HEADERS = [
	{ title: '分岗申请单号', key: 'BillCode', type: 'text', isCheck: true },
	{ title: '公司', key: 'OrgName', type: 'text', isCheck: true, width: '150' },
	{ title: '部门', key: 'GroupName', type: 'text', isCheck: true, width: '150' },
	{
		title: '审批状态',
		key: 'WorkflowStatus',
		type: 'tag',
		isCheck: true,
		tagType: (row: ISysHrJobAssignmentRequestBillView) => {
			const statusMap: Record<string, string> = {
				待提交: 'info',
				提交中: 'info',
				审核中: 'warning',
				已完成: 'success',
				已取消: 'danger',
			};
			return statusMap[row.WorkflowStatus || ''] || 'info';
		},
	},
	{ title: '单据状态', key: 'BillStatus', type: 'text', isCheck: true },
	{ title: '审批人', key: 'Approver', type: 'text', isCheck: true },
	{ title: '审批时间', key: 'ApprovalTime', type: 'text', isCheck: true },
	{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
] as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrJobAssignmentRequestBillQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const searchData = ref<ISysHrJobAssignmentRequestBillQuery>({});
const tableRef = ref();

/**
 * 表格行合并方法 - 性能优化版
 * 直接读取预处理的合并信息，避免重复计算
 * @param row 当前行数据
 * @param column 当前列配置
 * @param rowIndex 行索引
 * @param columnIndex 列索引
 * @returns [rowspan, colspan] 合并的行数和列数
 */
const spanMethod = ({ row, column }: { row: any; column: any; rowIndex: number; columnIndex: number }) => {
	const property = column.property;

	// 如果行数据中没有预处理的合并信息，则不合并
	if (!row._mergeInfo || !row._mergeInfo[property]) {
		return [1, 1];
	}

	const mergeInfo = row._mergeInfo[property];
	return [mergeInfo.rowspan, 1];
};

/**
 * 表格数据配置 - 响应式数据结构
 * 包含数据、表头配置和表格行为配置
 */
const tableData = ref({
	data: [] as ISysHrJobAssignmentRequestBillView[], // 表格数据
	header: TABLE_HEADERS, // 表头配置
	config: {
		total: 0, // 总记录数
		loading: true, // 加载状态
		isSerialNo: true, // 显示序号列
		isSelection: true, // 显示选择列
		isOperate: props.isDisabled, // 根据禁用状态决定是否显示操作列
		isStripe: false, // 开启斑马纹
	},
});

// 计算属性 - 判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

/**
 * 数据预处理 - 计算合并信息
 * 在获取数据后立即处理，避免在渲染时重复计算
 */
const processTableData = (data: ISysHrJobAssignmentRequestBillView[]) => {
	const mergeFields = ['BillCode', 'OrgName', 'GroupName', 'WorkflowStatus', 'BillStatus', 'Approver', 'ApprovalTime', 'Remark'];

	return data.map((row, index) => {
		// 为每行添加合并信息
		const mergeInfo: Record<string, { rowspan: number; show: boolean }> = {};

		mergeFields.forEach((field) => {
			// 检查是否与上一行相同
			const shouldHide =
				index > 0 &&
				mergeFields.every(
					(f) => data[index][f as keyof ISysHrJobAssignmentRequestBillView] === data[index - 1][f as keyof ISysHrJobAssignmentRequestBillView]
				);

			if (shouldHide) {
				// 当前行应该隐藏
				mergeInfo[field] = { rowspan: 0, show: false };
			} else {
				// 计算向下合并的行数
				let rowspan = 1;
				for (let i = index + 1; i < data.length; i++) {
					const shouldMerge = mergeFields.every(
						(f) => data[index][f as keyof ISysHrJobAssignmentRequestBillView] === data[i][f as keyof ISysHrJobAssignmentRequestBillView]
					);
					if (shouldMerge) {
						rowspan++;
					} else {
						break;
					}
				}
				mergeInfo[field] = { rowspan, show: true };
			}
		});

		// 判断是否是合并组的第一行
		const isFirstRow = !mergeFields.some((field) => mergeInfo[field].rowspan === 0);

		// 计算当前行在合并组中的位置，判断是否为中间行
		let isMiddleRow = false;
		if (isFirstRow) {
			// 如果是第一行，直接判断中间位置
			const rowspan = Object.values(mergeInfo)[0]?.rowspan || 1;
			const middleIndex = Math.floor((rowspan - 1) / 2);
			isMiddleRow = middleIndex === 0; // 第一行同时也是中间行
		} else {
			// 如果不是第一行，需要计算在合并组中的相对位置
			let groupStartIndex = index;
			// 向前查找合并组的开始位置
			while (groupStartIndex > 0) {
				const prevMatches = mergeFields.every(
					(f) =>
						data[groupStartIndex - 1][f as keyof ISysHrJobAssignmentRequestBillView] === data[index][f as keyof ISysHrJobAssignmentRequestBillView]
				);
				if (prevMatches) {
					groupStartIndex--;
				} else {
					break;
				}
			}

			// 计算合并组的总行数
			let groupRowspan = 1;
			for (let i = groupStartIndex + 1; i < data.length; i++) {
				const shouldMerge = mergeFields.every(
					(f) => data[groupStartIndex][f as keyof ISysHrJobAssignmentRequestBillView] === data[i][f as keyof ISysHrJobAssignmentRequestBillView]
				);
				if (shouldMerge) {
					groupRowspan++;
				} else {
					break;
				}
			}

			// 计算当前行在合并组中的相对位置
			const positionInGroup = index - groupStartIndex;
			const middleIndex = Math.floor((groupRowspan - 1) / 2);
			isMiddleRow = positionInGroup === middleIndex;
		}

		return {
			...row,
			_mergeInfo: {
				...mergeInfo,
				isFirstRow, // 添加是否为第一行的标识
				isMiddleRow, // 添加是否为中间行的标识
			},
		};
	});
};

// 创建自定义的搜索API函数，确保数据预处理
const customSearchApi = async (searchParams: any) => {
	// 调用原始API
	const response = await api().search(searchParams);

	// 预处理数据
	const rawData = (response.Data || []) as ISysHrJobAssignmentRequestBillView[];
	const processedData = processTableData(rawData);

	// 返回处理后的数据
	return {
		...response,
		Data: processedData,
	};
};

// 初始化表格数据
const getTableData = async () => {
	try {
		// 确保表格组件始终使用我们的自定义搜索API
		if (tableRef.value) {
			// 只调用一次doSearch，让WtmTable组件管理数据
			await tableRef.value.doSearch(customSearchApi, searchData.value);
		} else {
			// 如果表格组件还未初始化，手动调用API并设置数据
			tableData.value.config.loading = true;
			const response = await customSearchApi(searchData.value);
			tableData.value.data = response.Data;
			tableData.value.config.total = Number((response as any).Count || 0);
			tableData.value.config.loading = false;
		}
	} catch (error) {
		handleError(error);
		tableData.value.config.loading = false;
	}
};

// 对话框操作
const OnCreateClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.add') || '新增', CreateDialog, null, getTableData, '70%');
};

const OnEditRowClick = (row: ISysHrJobAssignmentRequestBillView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.edit') || '编辑', EditDialog, row, getTableData, '70%');
};

const OnDetailsRowClick = (row: ISysHrJobAssignmentRequestBillView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.detail') || '详情', DetailsDialog, row, getTableData, '70%');
};

const OnImportClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.import') || '导入', ImportDialog, null, getTableData, '70%');
};

// 删除操作
const onDelete = async (row: ISysHrJobAssignmentRequestBillView) => {
	try {
		const ids = [row.ID] as (string | number)[];
		await api().delete(ids);
		getTableData();
	} catch (error) {
		handleError(error);
	}
};

// 批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrJobAssignmentRequestBillView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy?.$t('message._system.common.vm.error') || '操作失败');
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要删除的数据');
	}
};

// 导出操作
const onExport = () => {
	const selected = tableRef.value?.getSelectedRows();
	if (selected && selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 判断是否应该显示操作按钮（在合并行的中间位置显示）
const shouldShowOperationButtons = (row: ISysHrJobAssignmentRequestBillView, index: number): boolean => {
	const rowWithMergeInfo = row as any;
	if (!rowWithMergeInfo._mergeInfo) {
		// 如果没有合并信息，始终显示按钮
		return true;
	}

	// 只在合并组的中间行显示操作按钮
	return rowWithMergeInfo._mergeInfo.isMiddleRow;
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	try {
		await getTableData();

		// 确保表格组件初始化后使用我们的自定义搜索API
		// 这样分页、刷新等操作也会使用预处理逻辑
		nextTick(() => {
			if (tableRef.value) {
				// 重新设置搜索API，确保后续的分页操作使用预处理逻辑
				tableRef.value.doSearch(customSearchApi, searchData.value);
			}
		});
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
});
</script>
